package com.pin.zheng.xingmulibrary.http.net;


import android.text.TextUtils;

import androidx.annotation.NonNull;


import com.pin.zheng.xingmulibrary.BuildConfig;
import com.pin.zheng.xingmulibrary.PinZhengBase;
import com.pin.zheng.xingmulibrary.http.interfaces.APIService;
import com.pin.zheng.xingmulibrary.util.DeviceUuidFactory;
import com.pin.zheng.xingmulibrary.util.LogUtils;

import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.X509TrustManager;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;


public class RetrofitClient<T> {

    private static volatile RetrofitClient instance;
    //    private APIService apiService;
    private T apiService;
    private String baseUrl = PinZhengBase.getBaseUrl();
    private Retrofit retrofit;
    private OkHttpClient okHttpClient;

    private RetrofitClient() {
    }

    public static RetrofitClient getInstance() {
        if (instance == null) {
            synchronized (RetrofitClient.class) {
                if (instance == null) {
                    instance = new RetrofitClient();
                }
            }
        }
        return instance;
    }

    /**
     * 设置Header
     *
     * @return
     */
    private Interceptor getHeaderInterceptor() {
        return new Interceptor() {
            @Override
            public Response intercept(@NonNull Chain chain) throws IOException {
                Request original = chain.request();
                Request.Builder requestBuilder = original.newBuilder();
                if (TextUtils.isEmpty(PinZhengBase.getToken())) {
                    Request request = requestBuilder
                            .addHeader("Content-Type", "application/json; charset=UTF-8")
                            .addHeader("deviceId", DeviceUuidFactory.getUUID())
                            .build();
                    return chain.proceed(request);
                } else {
                    Request request = requestBuilder
                            .addHeader("Authorization", PinZhengBase.getToken())
                            .addHeader("Content-Type", "application/json; charset=UTF-8")
                            .build();
                    return chain.proceed(request);
                }
            }
        };

    }

    /**
     * 设置拦截器 打印日志
     *
     * @return
     */
//    private Interceptor getInterceptor() {
//
//        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
//        //显示日志
//        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
//
//        return interceptor;
//    }

    /**
     * 设置拦截器 打印日志
     *
     * @return
     */
    private Interceptor getInterceptor() {

//        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(
                new HttpLoggingInterceptor.Logger() {

                    @Override
                    public void log(String message) {
                        LogUtils.e(message);
                    }

                });
        //显示日志
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        return interceptor;
    }

    public OkHttpClient getOkHttpClient() {
        if (okHttpClient == null) {
            //如果为DEBUG 就打印日志
            if (PinZhengBase.getDeBug()) {
                okHttpClient = new OkHttpClient().newBuilder()
                        .connectTimeout(15000L, TimeUnit.MILLISECONDS)
                        .readTimeout(15000, TimeUnit.MILLISECONDS)
                        //设置Header
                        .addInterceptor(getHeaderInterceptor())
                        //设置拦截器
                        .addInterceptor(getInterceptor())
                        .sslSocketFactory(SSLSocketClient.getSSLSocketFactory(), new X509TrustManager() {
                            @Override
                            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

                            }

                            @Override
                            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

                            }

                            @Override
                            public X509Certificate[] getAcceptedIssuers() {
                                return new X509Certificate[0];
                            }
                        })//配置
                        .hostnameVerifier(SSLSocketClient.getHostnameVerifier())//配置
                        .build();
            } else {
                okHttpClient = new OkHttpClient().newBuilder()
                        .connectTimeout(15000, TimeUnit.MILLISECONDS)
                        .readTimeout(15000L, TimeUnit.MILLISECONDS)
                        //设置Header
                        .addInterceptor(getHeaderInterceptor())
                        .sslSocketFactory(SSLSocketClient.getSSLSocketFactory(), new X509TrustManager() {
                            @Override
                            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

                            }

                            @Override
                            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

                            }

                            @Override
                            public X509Certificate[] getAcceptedIssuers() {
                                return new X509Certificate[0];
                            }
                        })//配置
                        .hostnameVerifier(SSLSocketClient.getHostnameVerifier())//配置
                        .build();
            }

        }

        return okHttpClient;
    }

    public T getApi() {
        //初始化一个client,不然retrofit会自己默认添加一个
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    //设置网络请求的Url地址
                    .baseUrl(baseUrl)
                    .addConverterFactory(ConverterFactory.create())
                    //设置数据解析器
                    .addConverterFactory(GsonConverterFactory.create())
                    //设置网络请求适配器，使其支持RxJava与RxAndroid
                    .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
                    .client(getOkHttpClient())
                    .build();
        }
        //创建—— 网络请求接口—— 实例
        if (apiService == null) {
            apiService = (T) retrofit.create(PinZhengBase.getApiservice());
        }

        return apiService;
    }


}
